package com.quotes.indicators;

import java.util.*;
import com.quotes.datamodell.TimeSeries;

public class TimeSeriesCalculator 
{
	public static TimeSeries calculateSimpleMovingAverage(TimeSeries input, int ticks) {
		TimeSeries result = new TimeSeries();
		
		Date[] keys = input.DatesAsArray();
		for (int i=ticks-1; i<keys.length; i++) {
			double sma = 0;
			for (int u=i; u>=i-ticks+1; u--) {
				sma += input.get(keys[u]);
			}
			
			sma = sma / ticks;
			result.put(keys[i], sma);
		}
		
		return result;
	}

	private static double calculateExponentialMovingAverage(double multiplier, double[] data, int index) {
		if (index == 0)
			return data[0];
		
		return multiplier * data[index] + (1 - multiplier) * calculateExponentialMovingAverage(multiplier, data, index - 1);
	}
	
	public static TimeSeries calculateExponentialMovingAverage(TimeSeries input, int ticks) {
		TimeSeries result = new TimeSeries();
		double multiplier = 2.0 / (ticks + 1);
		double[] data = input.ValuesAsArray();
		Date[] keys = input.DatesAsArray();
		
		for (int i=0; i<data.length; i++) {
			result.put(keys[i], calculateExponentialMovingAverage(multiplier, data, i));
		}
	
		return result;
	}
	
	public static TimeSeries calculateMovingMaximum(TimeSeries series, int ticks) {
		TimeSeries result = new TimeSeries();
		Date[] dates = series.DatesAsArray();
		
		for (int i=0; i<series.size(); i++) {
			TimeSeries range = series.extract(dates[i], ticks);
			result.put(dates[i], range.getMaxValue());
		}
		
		return result;
	}
	
	public static TimeSeries calculateMovingMinimum(TimeSeries series, int ticks) {
		TimeSeries result = new TimeSeries();
		Date[] dates = series.DatesAsArray();
		
		for (int i=0; i<series.size(); i++) {
			TimeSeries range = series.extract(dates[i], ticks);
			result.put(dates[i], range.getMinValue());
		}
		
		return result;
	}
}
